<?php

namespace app\web\controller;

use think\Loader;
use think\Cache;
use think\Controller;
use think\Db;
use think\response\Json;
use think\Session;

use QL\QueryList;
use QL\Ext\PhantomJs;

use app\common\model\Sogou as SogouModel;
use app\common\model\Baidu as BaiduModel;
use app\common\model\Sm as SmModel;
use app\common\model\AdminUser as AdminUserModel;
use app\common\model\View as ViewModel;
/**
 * 后台公用基础控制器
 * Class AdminBase
 * @package app\common\controller
 */
class Js extends Controller
{
    private $id;
    private $sign;
    private $data;
    private $setting;
    protected function _initialize()
    {
        parent::_initialize();
        // 获取 ID
        $this->id = input('sign',null,'unlock');
        $this->sign = input('sign',null);

//        if(is_null($this->id)) exit() ;

        $model = new AdminUserModel();
        $this->data = $model->get(['id'=>$this->id]);
        if(!empty($this->data->setting)){
            $this->setting = $this->data->setting;
        }
        // $this->collectUserInfos();
    }

    private function getData($id){
        $model = new AdminUserModel();
        $res = $model->get(['id'=>$id]);
        return $res;
    }

    private function getStyleData($id){
        $this->model = new ViewModel();
        $data_lists  = $this->model->get(['uid'=>$id,'isuse'=>1]);
        return $data_lists;
    }
    /**
     * 检测访问当前页面的权限  【个人感觉不用限制】
     */
    protected function checkAuth()
    {

        $endtime =$this->data->endtime;
        if($endtime - time() < 0){die('/**die end*/');}


        $setting = $this->data->setting;

        if(!checkTime($setting["opentime"])){
            echo "/**die time*/";
            exit();
        }


        $ip = getRealIp();
        $dis_ips = explode("\r\n",$setting["ips"]);
        if(count($dis_ips) > 30){
            $dis_ips = array_slice($dis_ips,0,30);
        }

        if( in_array($ip,$dis_ips) ){
            echo "/**die ip*/";
            exit();
        }

        $ipInfo = getIpInfo($ip);

        if( !in_array($ipInfo["province"],$setting["area"]) ){
            echo "/**die area*/";
            // exit();
        }

    }
    /**
     * 收集用户信息
     */
    protected function collectUserInfos(){
        if (!session(md5($this->id))) {
            session(md5($this->id),true);

            $data = [];
            $data['ua'] = $_SERVER['HTTP_USER_AGENT'];
            $data['reffer'] = isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:""; //来源地址
            $data['ip'] = getRealIp(); //ip
            $ipInfo = getIpInfo($data['ip']);
            $data['area'] = $ipInfo["province"]?$ipInfo["province"]:'未知'; //地区
            $data['keyword'] = getKeyWord($data['reffer']); //关键词
            $data['searchType'] = getSearchType($data['reffer']); //搜索引擎类型
            $data['addtime'] = time(); //访问时间

            $prefix = config('database.prefix');
            $database = config('database.database');
            $table = $prefix.$this->id.'_tj';
            $is_table = Db::query( 'SELECT COUNT(*) as c FROM information_schema.tables WHERE table_schema = "'.$database.'" AND table_name = "'.$table.'" ;' );
            $is_table = $is_table[0]['c'];

            if (!$is_table) {
                $sql = "
                CREATE TABLE `{$table}` (
                `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                `addtime` int(11) NOT NULL DEFAULT '0',
                `reffer` varchar(255) NOT NULL DEFAULT '',
                `ua` varchar(255) NOT NULL DEFAULT '',
                `keyword` varchar(20) DEFAULT '' COMMENT '关键词',
                `searchType` int(11) DEFAULT '0' COMMENT '搜索引擎类型',
                `area` varchar(10) NOT NULL COMMENT '地域如青海',
                `ip` varchar(20) NOT NULL COMMENT 'ip地址',
                PRIMARY KEY (`id`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
            //Db::execute($sql) ;
        }

          // Db::table($table)->insert($data);
        }

    }


    public  function getJs()
    {

        $this->checkAuth();
        $data = [
            'id' =>$this->id,
//            'bj' => $this->data['bj'],
//            'keyword'=>$this->data['keyword']
            ];
        $data['host'] = config("view_replace_str.__HOST__");
        $data['sign'] = $this->sign;
        $data['ystime']=$this->setting['ystime']*1000;
        $data['js']=$this->setting['js'];
        $data['swtjs']=$this->setting['swtjs'];

        return view('js/dialog',$data);
    }

    public function eval_my(){
        $data = $this->request->post();
        if (isset($data['data'])){
            $data = json_decode(html_entity_decode($data['data']),true);
        }
        $data['host'] = config("view_replace_str.__HOST__");

        //合并公共设置
        $u_data = $this->getData(unlock($data['sign']))->setting;
        $data = array_merge($data,$u_data);

        //合并样式设置
//        if(is_null( $this->getStyleData(unlock($data['sign'])) )) die('/**no-default*/');
//        $s_data = $this->getStyleData(unlock($data['sign']))->content;


//        $data = array_merge($data,$s_data);
        $data['userico'] = '';
        //dump($data);
        $do = $this->getDo($data);
        $html = $this->getHtml($data);
        $datas = [
            'code'=>0,
            "msg"=>'',
            "do"=>$do,
            "html"=>$html
        ];
        return json_encode($datas);
    }

    protected function getDo($data){
        return $this->fetch('js/do',$data);
    }

    protected function getHtml($data){
//        此处根据收到的样式类型换不同的模板
        return $this->fetch('js/html',$data);
    }
}
